// packageA/pages/dataCollectorSend/dataCollectorSend.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../../utils/util');
import Base64 from '../../../utils/Base64.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {  
		//当前登录用户
		user: null,  
    //修改信息回显
    editInfo:{},
    //提交按钮禁用
    disabled:false,
		//添加的循环列表
    loopList: [{
      imei: null,
			num: 1,
			state: 0
		}],
		//避免表单重复提交
    code:null,		
		//选择框
    showSelect:false,
    //选择数据
    selectList:[],
    //当前选择
    selectField:'',
    //选择框标题
    selectTitle:'',
    //显示选择搜索框
    showSelectSearch:false,
    //选择框搜索
    valueSearch: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
		this.setData({
			//当前登录用户
			user: app.globalData.userInfo,
			//避免表单重复提交
			code:Base64.encode(new Date() + app.globalData.userInfo.userName)
		})
  },

  //提交表单##
  async confirmForm(e){
    //避免表单重复提交-先禁用按钮
    this.setData({
      disabled:true
    })
	
		let obj = e.detail.value;
    let td = this.data;
		let editInfo = td.editInfo;
		let list = td.loopList;
		let user = td.user;	

		//出库仓库必填
		if(!editInfo.warehouse){
			Toast.fail('请选择出库仓库');
			return;
		}

		//入库方必填
		if(!editInfo.factory){
			Toast.fail('请选择入库方');
			return;
		}

		//申请人必填
		if(!editInfo.applicantUser){
			Toast.fail('请选择申请人');
			return;
		}		

		if(list.length){
			//验证每一条都不为空
			let isNotNull = list.every(val=>{
				return val.imei
			});

			if(isNotNull){
				//验证当前输入的名称无重复
				let isR = this.isRepeat(list);
				if(isR){
					Toast.fail('模块不能重复');
					return;
				}else{
					//校验是否在仓库
					let isR2 = await this.isExist(list);
					if(!isR2){
						Toast.fail('录入模块不在仓库');
						return;
					}
				}
			}else{
				Toast.fail('请输入物联网编码');
				return;
			}
		}
		
		//自动生成出库单号 时间戳：LD + yyyymmdd + AUTOCJ + hhmmss
		let now = new Date();
		let nowYear = now.getFullYear();
		let nowMonth = (now.getMonth() + 1).toString().length > 1 ? now.getMonth() + 1 : "0" + (now.getMonth() + 1).toString();
		let nowDay = now.getDate().toString().length > 1 ? now.getDate() : "0" + now.getDate().toString();
		let nowHours = now.getHours().toString().length > 1 ? now.getHours() : "0" + now.getHours().toString();
		let nowMinutes = now.getMinutes().toString().length > 1 ? now.getMinutes() : "0" + now.getMinutes().toString();
		let nowSeconds = now.getSeconds().toString().length > 1 ? now.getSeconds() : "0" + now.getSeconds().toString();
		let deliveryOrderNo = "LD" + nowYear + nowMonth + nowDay + "AUTOCJ" + nowHours + nowMinutes + nowSeconds;

		let param={
      className:'imeiWarehouseInFactoryM',
      data:{
				requestToken: td.code,
				id: null,
        //操作者
				currentUser: {
					id: user.id,
					userName: user.userName
				},
				//出库单号
				deliveryOrderNo: deliveryOrderNo,
				//出库仓库
				warehouseId: editInfo.warehouse.id,
				//入库方
				factoryId: editInfo.factory.id,
				factory: {
					id: editInfo.factory.id,
					departName: editInfo.factory.name
				},
				//申请人
				applicantUser: {
					id: editInfo.applicantUser.id,
					userName: editInfo.applicantUser.userName
				},
				//数量
				num: list.length,
				//备注
				remark: obj.remark.trim(),
				//问题类型
				issueType: 2,
				//模块列表
				childarr: list
      }
    }

		// console.log(param);
    // return;

    //避免表单重复提交
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '数据提交中...'
    });

    CommonService.goSave(param).then(res=>{
      this.setData({
        disabled:false
      })
      if (res.statusCode == 200 && res.data.success == true){
				Toast.success('成功');

				//更新仓库
				this.updateWarehouse(param.data);

        setTimeout(() => {
          //返回列表页并刷新数据
          this.backAndRefresh();
        }, 1000);
      }else if(res.statusCode==202){
        Toast.fail('您操作太快了,请勿重复提交');
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })
	},

  //返回列表页并刷新数据
  backAndRefresh(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];

    prevPage.refreshListAndPage();
    wx.navigateBack();
  },  
	
	//添加循环数据
  async onAddLoop(){		
		let list = this.data.loopList;
		if(list.length){
			//验证每一条都不为空
			let isNotNull = list.every(val=>{
				return val.imei
			});

			if(isNotNull){
				//验证当前输入的名称无重复
				let isR = this.isRepeat(list);
				if(isR){
					Toast.fail('模块不能重复');
					return;
				}else{
					//校验是否在仓库
					let isR2 = await this.isExist(list);
					if(!isR2){
						Toast.fail('录入模块不在仓库');
						return;
					}
				}
			}else{
				Toast.fail('请输入物联网编码');
				return;
			}
		}
		
		//增加一条
		list.push({
			imei: null,
			num: 1,
			state: 0
		});

		this.setData({ 
			loopList: list,
			disabled: false
		})
	},

	//用户输入时清除错误提示
  clearMessage(e) {
    let field = e.target.dataset.message;
    let obj = {};
    obj[field] = "";
    obj['disabled'] = false;
    this.setData(obj);
  },
	
	//获取输入的内容
	onGetValue(e){
    let idx=e.currentTarget.dataset.index;
    let val=e.detail;
    let sList=this.data.loopList;
   
    sList.forEach((item,index) => {
      if(index==idx){
        item.imei=val.trim();
      }
    }); 

    this.setData({ 
			loopList: sList,
			disabled: false
	  })
	},
	
	//扫码
	scanCode(e){
		let that = this;
		let idx = e.currentTarget.dataset.index;
		let sList = this.data.loopList;
		let val = '';

		wx.scanCode({
      success: (res) => {
				val = res.result;
				
				sList.forEach((item,index) => {
					if(index==idx){
						item.imei = val;
					}
				});
				
				that.setData({ 
					loopList: sList,
					disabled: false
				})
      }
    })
	},

  //删除循环数据
  onDeleteLoop(e){    
    let idx=e.currentTarget.dataset.index;
    let sList=this.data.loopList;
    let arr=[];
    
    sList.forEach((item,index) => {
      if(index!=idx){
        arr.push(item);
      }
    });

    this.setData({ 
			loopList: arr,
			disabled: false
    })
	},

	//验证imei是否重复
	isRepeat(arr) {
		let hash = {};
		for(let i in arr) {
			if(hash[arr[i].imei]) {
				return true;
			}	
			hash[arr[i].imei] = true;	
		}
		return false;
	},

	//验证模块是否在仓库
  async isExist(list){
		//把编码拿出来
		let arr = [];
		list.forEach(item=>{
			arr.push(item.imei);
		});

    let param={
      isAuth:true,
      className:'imeiWarehouse',
      data:{
				imei: arr,
				warehouseId: this.data.editInfo.warehouse.id,
        selectFields:['id']
      }
    }

    return new Promise((resolve, reject) => {
      CommonService.goFindList(param).then(res=>{
        if (res.data.data && res.data.data.result && res.data.data.result.length) {
					if(res.data.data.result.length==arr.length){
						resolve(true);
					}else{
						resolve(false);
					}
        } else {
          resolve(false);
        }
      }).catch((error) => {
        resolve(false);
      })
    });
	},
	
	//显示选择框
  onShowSelect(e){
    this.setData({
      selectList: []
    })

    let dataset=e.currentTarget.dataset;
    let field=dataset.field;

    this.setData({
      showSelect: true,
      selectField: field
    })

    //出库仓库
    if(field=='warehouse'){
      this.setData({
        selectTitle: '出库仓库',
        showSelectSearch: false
      })
      this.getWarehouseList();
		}
		
		//入库方
    if(field=='factory'){
      this.setData({
        selectTitle: '入库方',
        showSelectSearch: true
      })
      this.getFactoryList();
		}
		
		//申请人
    if(field=='applicantUser'){
      this.setData({
        selectTitle: '申请人',
        showSelectSearch: true
      })
      this.getUserList();
    }
  },

  //隐藏选择框
  onCloseSelect(){
    this.setData({
      showSelect: false,
      valueSearch: '',
      disabled: false
    })
  },

  //确认选项
  onConfirmSelect(e){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;

    //出库仓库
    if(selectField=='warehouse'){
      obj='editInfo.warehouse';
		}
		
		//入库方
    if(selectField=='factory'){
      obj='editInfo.factory';
		}
		
		//申请人
    if(selectField=='applicantUser'){
      obj='editInfo.applicantUser';
    }

    if(id && name){
      this.setData({
        [id]:e.detail.value.id,
        [name]:e.detail.value.text
      })
    }

    if(obj){
      this.setData({
        [obj]:e.detail.value.obj
      })
    }

    this.onCloseSelect();
  },

  //选择框搜索
  onChangeSelectVal(e){
    let selectField=this.data.selectField;

    this.setData({
      valueSearch: e.detail
		}) 
		
		//入库方
    if(selectField=='factory'){
      this.getFactoryList();
		}
		
		//申请人
    if(selectField=='applicantUser'){
      this.getUserList();
    }
  },

  //查询仓库
  getWarehouseList(){
    let param = {
      isAuth: true,
      className: 'warehouse',
      data: {
        searchAll: true,
        selectFields: ['id','name']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:{
              id:item.id,
              name:item.name
            }
          });
        });

        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
	},
	
	//查询入库方
  getFactoryList(){
    let param = {
      isAuth: true,
      className: 'depart',
      data: {
				id:{">=":100000},
        searchAll: true,
        selectFields: ['id', 'name', 'type', 'level', 'companyId', 'count']
      }
    }

    if(this.data.valueSearch){
      param.data.name='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text: item.name,
            id: item.id,
            obj: item
          });
        });

        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
	},
	
	//查询申请人
  getUserList(){
    let param = {
      isAuth: true,
      className: 'user',
      data: {
				//只查蓝涤物联网的人员
				depart: 1938,
        searchAll: true,
        selectFields: ["id", "userName", "departName"]
      }
    }

    if(this.data.valueSearch){
      param.data.userName='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text: item.userName,
            id: item.id,
            obj: item
          });
        });

        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
	},
	
	//更新仓库
	updateWarehouse(obj){
		//编码列表
		let arr = [];
		obj.childarr.forEach(item=>{
			arr.push(item.imei);
		});

		let param = {
      className: 'imeiWarehouse',
      data: {
        filter: {
          imei: arr
        },
        update: {
          set: {
						//出库方
						factoryId: obj.factoryId,
						//类型
						issueType: 2,
						//仓库
						warehouseId: 0,
						warehouse: {
							id: obj.factory.id,
							departName: obj.factory.departName
						},
						//日期
						outDate: util.timeFormat(new Date()),
						//操作记录
						operationLog: {
							push: {
								time: util.timeFormat(new Date()),
								operationUser: obj.applicantUser.userName,
								operationEvent: "出库"
							}
						}
          }
        }
      }
		}		

		CommonService.goUpdate(param).then(res => {
    }).catch((error) => {
    })
	},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})